<template lang="pug">
    el-select(v-model="selected_val" :disabled="field.readonly" @change="on_change")
        el-option(v-for="option in field.options" :key="option.label" :value="option.val" :label="option.label")
</template>
<script>
import axios from "../../../../plugins/axios";

export default {
  name: "selection-field",

  data() {
    return {
      selected_val: null
    };
  },

  props: {
    field: {
      type: Object,
      default: () => {
        return {};
      }
    },

    value: {  }
  },

  model: { prop: "value", event: "update" },

  watch: {
    field(val) {
      this.try_parse_source();
    },

    selected_val(val) {
      if (this.value !== val) this.$emit("update", val); // 更新模型
    },

    value(val) {
      if (this.selected_val !== val) this.selected_val = val; // 更新数据
    }
  },

  methods: {
    // 把action地址请求出数据
    try_parse_source() {
      const source = this.field.source;
      if (!source || !source.action) return; // 没配置请求地址，返回

      const options = { url: source.action };
      var vm = this;
      axios(options)
        .then(res => {
          vm.map_to_options(res);
        })
        .catch(err => console.log(err));
    },

    // 获取到的数据转换成options格式数据
    map_to_options(selection_data) {
      const source = this.field.source;
      const select_options = [];

      selection_data.forEach(item => {
        select_options.push({
          label: source.labelMap ? item[source.labelMap] : item.label,
          val: source.valueMap ? item[source.valueMap] : item.val
        });
      });

      this.field.options = select_options;
      console.log(this.field.options);
    },

    on_change() {
      //   this.field.val = value;
      this.$emit("update", this.selected_val);
    }
  },

  created() {
    if (!this.field) return;
    this.field.options = this.field.options || [];
    this.try_parse_source();

    if (this.field.val) this.selected_val = this.field.val;
  }
};
</script>